'''
pip install requests
pip install lxml
阴阳师壁纸xpath
//div[@class="tab-cont"]/div/div/img/@data-src
'''
import requests
from lxml import etree
import os


def mkdirIfNotExists(path):
    if not os.path.exists(path):
        os.mkdir(path)


horizontalPicsPath = 'project/yys/horizontalPics'
verticallyPicsPath = 'project/yys/verticallyPics'
mkdirIfNotExists(horizontalPicsPath)
mkdirIfNotExists(verticallyPicsPath)


# 伪装成浏览器请求
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36 Edg/107.0.1418.52'}
picHtml = requests.get(
    'https://yys.163.com/media/picture.html', headers=headers)
e = etree.HTML(picHtml.text)
# https://yys.res.netease.com/pc/zt/20170731172708/data/picture/4/9/640x960.jpg
horizontalPics = [picUrl[:picUrl.rindex('/')]+'/2732x2048.jpg' for picUrl in e.xpath(
    '//div[@class="tab-cont"][1]/div/div/img/@data-src')]
verticallyPics = [picUrl[:picUrl.rindex('/')]+'/1080x1920.jpg' for picUrl in e.xpath(
    '//div[@class="tab-cont"][2]/div/div/img/@data-src')]


def downloadPics(path, *pics, **headers):
    num = 1
    for picUrl in pics:
        print('downloading no.{} picUrl:{} to path:{}'.format(num, picUrl, path))
        resp = requests.get(picUrl, headers=headers)
        fileName = picUrl[picUrl.rindex('picture'):picUrl.rindex(
            '/')].replace('/', '_') + ".jpg"
        with open(f'{path}/{fileName}', 'wb') as f:
            f.write(resp.content)
            num += 1


downloadPics(verticallyPicsPath, *verticallyPics, **headers)
